package validjson;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringValidator implements Validator {
    private Schema schema;

    public StringValidator(Schema schema) {
        this.schema = schema;
    }

    public void validate(Object jsonToValidate) throws ValidationException {
        if (!(jsonToValidate instanceof String)) {
            throw new ValidationException(String.format("Validator expected a value of type '%s' but got %s", "String", jsonToValidate == null ? null : jsonToValidate.getClass()));
        }

        String string = (String)jsonToValidate;

        if (schema.containsKey("pattern")) {
            Pattern pattern = Pattern.compile((String) schema.getValue("pattern"));
            Matcher matcher = pattern.matcher(string);
            if (!matcher.matches()) {
                throw new ValidationException("Value '" + string + "' does not match pattern " + pattern.pattern());
            }
        }

        if (schema.containsKey("maxLength")) {
            long maxLength = ((Number)schema.getValue("maxLength")).longValue();
            if (string.length() > maxLength) {
                throw new ValidationException("Value '" + string + "' is longer than maximum length " + maxLength);
            }
        }

        if (schema.containsKey("minLength")) {
            long minLength = ((Number)schema.getValue("minLength")).longValue();
            if (string.length() < minLength) {
                throw new ValidationException("Value '" + string + "' is longer than minimum length " + minLength);
            }
        }

        if (schema.containsKey("enum")) {
            Set<String> allowedValues = new HashSet<String>((List<String>)schema.getValue("enum"));
            if (!allowedValues.contains(string)) {
                throw new ValidationException("Value '" + string + "' is not part of the valid set of enumeration values " + allowedValues);
            }
        }
    }
}
